<?php
require_once '../includes/functions.php';
check_login();

header('Content-Type: application/json');

// 获取POST数据
$data = json_decode(file_get_contents('php://input'), true);
$template_name = $data['name'] ?? '';

if (empty($template_name)) {
    http_response_code(400);
    echo json_encode(['error' => '模板名称不能为空']);
    exit;
}

// 验证模板名称格式
if (!preg_match('/^[a-zA-Z0-9-_]+$/', $template_name)) {
    http_response_code(400);
    echo json_encode(['error' => '模板名称只能包含字母、数字、连字符和下划线']);
    exit;
}

$template_path = get_template_path($template_name);

// 检查模板是否已存在
if (file_exists($template_path)) {
    http_response_code(400);
    echo json_encode(['error' => '模板已存在']);
    exit;
}

// 创建模板目录结构
$directories = [
    $template_path,
    $template_path . '/resources',
];

foreach ($directories as $dir) {
    if (!mkdir($dir, 0777, true)) {
        http_response_code(500);
        echo json_encode(['error' => '创建目录失败']);
        exit;
    }
}

// 创建初始的index.html文件
$initial_html = <<<HTML
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>广告落地页</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: #333;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        @media (max-width: 768px) {
            .container {
                padding: 10px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 在此处添加您的内容 -->
    </div>
</body>
</html>
HTML;

if (!file_put_contents($template_path . '/index.html', $initial_html)) {
    http_response_code(500);
    echo json_encode(['error' => '创建模板文件失败']);
    exit;
}

// 创建资源信息文件
$resources_info = [];
if (!file_put_contents($template_path . '/resources/resources.json', json_encode($resources_info, JSON_PRETTY_PRINT))) {
    http_response_code(500);
    echo json_encode(['error' => '创建资源信息文件失败']);
    exit;
}

echo json_encode(['success' => true, 'message' => '模板创建成功']);
